using Local;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
using UnityEditor;
using UnityEngine;
using Newtonsoft.Json;
using Local.Editor;

public class HotUpdateSettingWindow : EditorWindow
{
    [SerializeField]
    private string m_Platform = "StandaloneWindows64";
    [SerializeField]
    private string[] m_DllsNames = null;
    [SerializeField]
    private bool m_Enable = false;

    //系列化对象的初始化
    SerializedObject serObj = null;
    SerializedProperty Platform = null;
    SerializedProperty DllsNames = null;
    SerializedProperty Enable = null;

    [MenuItem("HotUpdateTool/热更工具")]
    public static void Open()
    {
        EditorWindow.GetWindow<HotUpdateSettingWindow>();
    }
    private void OnGUI()
    {
        serObj.Update();  

        string m_DLLAssetsInfoAssetName = DLLsSaveInfoSetting.DEFAULT_ASSET_NAME;
        if (string.IsNullOrEmpty(Platform.stringValue))
        {
            Platform.stringValue = BuildTarget.StandaloneWindows64.ToString();
        }
        BuildTarget buildTarget = Enum.Parse<BuildTarget>(Platform.stringValue);
        Platform.stringValue = EditorGUILayout.EnumPopup("构建平台", buildTarget).ToString();

        EditorGUILayout.PropertyField(Enable, new GUIContent("是否更新DLL"));
        EditorGUILayout.PropertyField(DllsNames,new GUIContent("热更DLL文件名称，注意先后顺序"));

        serObj.ApplyModifiedProperties();
        if (GUILayout.Button("1、复制AOT元到热更文件夹"))
        {
            //if (!Directory.Exists("Assets/StreamingAssets"))
            //{
            //    Directory.CreateDirectory("Assets/StreamingAssets");
            //}

            //foreach (var dll in AOTGenericReferences.PatchedAOTAssemblyList)
            //{
            //    string sourceFile = $"HybridCLRData/AssembliesPostIl2CppStrip/{m_Platform}/{dll}";
            //    string destinationFile = $"Assets/StreamingAssets/{dll}";
            //    bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
            //    System.IO.File.Copy(sourceFile, destinationFile, isrewrite);
            //}
            //AssetDatabase.Refresh();

            if (!Directory.Exists(DLLsSaveInfoSetting.DEFAULT_AOT_PATH))
            {
                Directory.CreateDirectory(DLLsSaveInfoSetting.DEFAULT_AOT_PATH);
            }
            string path = DLLsSaveInfoSetting.DEFAULT_AOT_PATH;
            foreach (var dll in AOTGenericReferences.PatchedAOTAssemblyList)
            {
                string sourceFile = $"HybridCLRData/AssembliesPostIl2CppStrip/{m_Platform}/{dll}";
                string destinationFile = $"{path}/{dll}.bytes";
                bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
                System.IO.File.Copy(sourceFile, destinationFile, isrewrite);
            }
            AssetDatabase.Refresh();
        }
        if (GUILayout.Button("2、复制热更DLL到资源文件夹"))
        {
            if (!Directory.Exists(DLLsSaveInfoSetting.DEFAULT_PATH))
            {
                Directory.CreateDirectory(DLLsSaveInfoSetting.DEFAULT_PATH);
            }
            string path = DLLsSaveInfoSetting.DEFAULT_PATH;
            foreach (var name in m_DllsNames)
            {
                string sourceFile = $"HybridCLRData/HotUpdateDlls/{m_Platform}/{name}";
                string destinationFile = $"{path}/{name}.bytes";
                bool isrewrite = true; // true=覆盖已存在的同名文件,false则反之
                System.IO.File.Copy(sourceFile, destinationFile, isrewrite);
            }
            AssetDatabase.Refresh();
        }
        // 保存

        if (GUILayout.Button("3、刷新热更DLL资源信息文件"))
        {
            string path = DLLsSaveInfoSetting.DEFAULT_PATH;
            List<string> names = new List<string>();
            foreach (string name in m_DllsNames)
            {
                names.Add($"{path}/{name}.bytes");
            }
            List<string> aotNames = new List<string>();
            string aotpath = DLLsSaveInfoSetting.DEFAULT_AOT_PATH;
            foreach (string name in AOTGenericReferences.PatchedAOTAssemblyList)
            {
                aotNames.Add($"{aotpath}/{name}.bytes");
            }
            DLLAssetsInfo info = new DLLAssetsInfo() { Names = names,AOTNames = aotNames,Enable = m_Enable};
            if (!Directory.Exists(DLLsSaveInfoSetting.DEFAULT_PATH))
            {
                Directory.CreateDirectory(DLLsSaveInfoSetting.DEFAULT_PATH);
            }
            FileStream fileStream = new FileStream(m_DLLAssetsInfoAssetName, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8);
            sw.WriteLine(JsonConvert.SerializeObject(info, Formatting.Indented));
            sw.Close();
            fileStream.Close();
            AssetDatabase.Refresh();
        }
    }
    private void OnEnable()
    {
        serObj = new SerializedObject(this);
        Platform = serObj.FindProperty("m_Platform");
        DllsNames = serObj.FindProperty("m_DllsNames");
        Enable = serObj.FindProperty("m_Enable");
        //导入setting
        if (File.Exists(Path.Combine(HotUpdateSetting.GetSavePath(), "HotUpdateSetting.json")))
        {
            var setting = JsonConvert.DeserializeObject<HotUpdateSetting>(File.ReadAllText(Path.Combine(HotUpdateSetting.GetSavePath(), "HotUpdateSetting.json")));
            if (setting != null)
            {
                m_Platform = setting.m_Platform;
                m_DllsNames = setting.m_DllsNames;
                m_Enable = setting.m_Enable;
            }
        }
    }
    private void OnDisable()
    {
        //写入setting
        HotUpdateSetting hotUpdateSetting = new HotUpdateSetting() { m_Platform = m_Platform, m_DllsNames = m_DllsNames,m_Enable = m_Enable };
        string json = JsonConvert.SerializeObject(hotUpdateSetting, Formatting.Indented);
        if (!Directory.Exists(HotUpdateSetting.GetSavePath()))
        {
            Directory.CreateDirectory(HotUpdateSetting.GetSavePath());
        }
        FileStream fileStream = new FileStream(Path.Combine(HotUpdateSetting.GetSavePath(), "HotUpdateSetting.json"), FileMode.OpenOrCreate);
        StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8);
        sw.WriteLine(json);
        sw.Close();
        fileStream.Close();
    }

}
